package com.study.limiter;

import com.google.common.io.Files;
import com.study.locks.redis.JedisPoolUtil;
import org.springframework.core.io.ClassPathResource;
import redis.clients.jedis.Jedis;

import java.nio.charset.Charset;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

/**
 * 放入令牌 -> 使用定时任务完成
 *
 * @author: chenhs
 * @date: Created in 16:15 2020/2/2
 **/
public class JedisRateLimiterSeter implements AutoCloseable {

    private String luaScript;

    private Timer timer;

    private final Jedis jedis = JedisPoolUtil.getJedis();

    public JedisRateLimiterSeter(String scriptFile, String key, String limit) {

        try {
            luaScript = Files.asCharSource(new ClassPathResource(scriptFile).getFile(), Charset.forName("UTF-8")).read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        timer = new Timer();

        //放入令牌的时间间隔
        long period = 1000L / Long.valueOf(limit);

        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.out.println(System.currentTimeMillis() + "放入令牌：" + ((Long) jedis.eval(luaScript, 1, key, limit)));
            }
        }, period, period);
    }

    @Override
    public void close() {
        this.jedis.close();
        this.timer.cancel();
    }

    public static void main(String[] args) throws Exception {
        JedisRateLimiterSeter jrls = new JedisRateLimiterSeter("lua/rateLimiterSet.lua", "Mike-666999", "10");
        TimeUnit.SECONDS.sleep(10L);
        jrls.close();
    }

}
